package com.sgb.member.ui.fragment;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.google.android.material.tabs.TabLayout;
import com.sgb.member.MemberConfig;
import com.sgb.member.PickCateType;
import com.sgb.member.R;
import com.sgb.member.databinding.FragmentMemberEnterpriseServiceBinding;
import com.sgb.member.di.DaggerMemberFragComponent;
import com.sgb.member.di.MemberFragModule;
import com.sgb.member.entity.MemberServiceListBean;
import com.sgb.member.ui.activity.MemberBusinessActivity;
import com.sgb.member.ui.adapter.MemberServiceListAdapter;
import com.sgb.member.view_model.BusinessEnterpriseMode;
import com.swgk.core.base.AppLazyFragment;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.customview.XCustomTabLayout;
import com.swgk.core.recyclerview.adapter.AdapterOnItemClick;
import com.swgk.core.view.areapopup.AddressEntity;
import com.swgk.core.view.areapopup.GoodsSourceLocationEntity;
import com.swgk.core.view.areapopup.ThreeLevelAreaWindow;
import com.swgk.core.view.selection.CommonPopEntity;
import com.swgk.core.view.selection.MemberStatusView;
import com.swgk.core.xrecyclerview.LoadingMoreFooter;
import com.swgk.core.xrecyclerview.XRecyclerView;

import java.util.List;

import javax.inject.Inject;

/**
 * 会员经营-企业服务
 */
public class BusinessEnterpriseFragment extends AppLazyFragment
        implements MemberStatusView.OnChooseListener {

    @Inject
    public BusinessEnterpriseMode sModel;
    private FragmentMemberEnterpriseServiceBinding mBinding;
    private MemberServiceListAdapter mAdapter;
    private int mCurPos; // 主页面TAB下标
    private CommonPopEntity mEntity; // 主页面TAB下标

    private GoodsSourceLocationEntity mAddressEntity; // 装货地
    private ThreeLevelAreaWindow mAddressPop;
    private List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> scrData;

    private String mServiceId = "";
    private String mServiceId2 = "";
    private String mServiceId3 = "";
    private String mNo9 = "";//会员级别

    public static BusinessEnterpriseFragment newInstance(int position, CommonPopEntity entity) {
        BusinessEnterpriseFragment fragment = new BusinessEnterpriseFragment();
        Bundle bundle = new Bundle();
        bundle.putInt("INDEX", position);
        bundle.putSerializable("ENTITY", entity);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    protected void setupFragmentComponent(AppComponent appComponent) {
        DaggerMemberFragComponent.builder()
                .appComponent(appComponent)
                .memberFragModule(new MemberFragModule(this))
                .build()
                .inject(this);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_member_enterprise_service, container, false);
        mBinding.setLifecycleOwner(this);
        return mBinding.getRoot();
    }


    @Override
    protected void initView() {
        assert getArguments() != null;
        mCurPos = getArguments().getInt("INDEX", 0);
        mEntity = (CommonPopEntity) getArguments().getSerializable("ENTITY");
        if (mEntity != null) {
            mServiceId = mEntity.getId();
            if (mEntity.getChildren() != null && mEntity.getChildren().size() > 0) {
                showChildTab(mEntity.getChildren());
            }
        }
        initRecycler();
        initPopup();
    }

    @Override
    protected void onLazyLoad() {
        loadData(false);
        loadOtherData();
    }

    private void loadOtherData() {
        sModel.getMemberLevelData(PickCateType.TYPE_9, false); // 会员级别
    }

    public void loadData(boolean isLoadMore) {
        String text = ((MemberBusinessActivity) getActivity()).getSearchText();
        sModel.getEnterpriseServiceList(isLoadMore, text, mServiceId, mServiceId2, mServiceId3, mAddressEntity, mNo9);
    }

    private void showChildTab(List<CommonPopEntity> data) {
        if (data == null || data.size() == 0) {
            mBinding.childTabLayout.setVisibility(View.GONE);
            return;
        }
        mBinding.childTabLayout.removeAllTabs();
        mBinding.childTabLayout.clearOnTabSelectedListeners();
        mBinding.childTabLayout.setVisibility(View.VISIBLE);
        if (!data.get(0).getTypeName().equals("全部") && !data.get(0).getTypeName().equals("不限")) {
            data.add(0, new CommonPopEntity("", "全部"));
        }
        for (int i = 0; i < data.size(); i++) {
            mBinding.childTabLayout.addTab(mBinding.childTabLayout.newTab().setText(data.get(i).getTypeName()));
        }
        mBinding.childTabLayout.setNormalColor(R.color.color_title_small);
        mBinding.childTabLayout.addOnTabSelectedListener(data, new XCustomTabLayout.SimpleSelectedListener() {

            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                int pos = tab.getPosition();
                mServiceId2 = data.get(pos).getId();
                showChildThreeTab(data.get(pos).getChildren());
                loadData(false);
            }
        });
    }

    private void showChildThreeTab(List<CommonPopEntity> data) {
        if (data == null || data.size() == 0) {
            mBinding.childTabLayout2.setVisibility(View.GONE);
            return;
        }
        if (!data.get(0).getTypeName().equals("全部") && !data.get(0).getTypeName().equals("不限")) {
            data.add(0, new CommonPopEntity("", "全部"));
        }
        mBinding.childTabLayout2.setVisibility(View.VISIBLE);
        mBinding.childTabLayout2.removeAllTabs();
        mBinding.childTabLayout2.setOnTabSelectedListener(null);
        for (int i = 0; i < data.size(); i++) {
            mBinding.childTabLayout2.addTab(mBinding.childTabLayout2.newTab().setText(data.get(i).getTypeName()));
        }
        mBinding.childTabLayout2.setNormalColor(R.color.color_tab_three);
        mBinding.childTabLayout2.addOnTabSelectedListener(data, new XCustomTabLayout.SimpleSelectedListener() {

            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                int pos = tab.getPosition();
                mServiceId3 = data.get(pos).getId();
                loadData(false);
            }
        });
    }

    public void setAddressData(List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> data) {
        scrData = data;
        mAddressEntity = new GoodsSourceLocationEntity();
        mAddressPop.setData(scrData, true);
    }

    /**
     * -------------------------------------initRecycler------------------------------------------
     */
    private void initRecycler() {
        TextView textView = mBinding.emptyView.findViewById(R.id.no_data_count);
        textView.setVisibility(View.VISIBLE);
        mBinding.recyclerView.setPullRefreshEnabled(true);
        mBinding.recyclerView.setLoadingMoreEnabled(true);
        LoadingMoreFooter footer = (LoadingMoreFooter) mBinding.recyclerView.getFootView();
        footer.setNoMoreHint("已经到底啦~");
        mBinding.recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        mBinding.recyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                loadData(false);
            }

            @Override
            public void onLoadMore() {
                loadData(false);
            }
        });
        mAdapter = new MemberServiceListAdapter(getActivity(), null);
        mAdapter.setOnItemClick(new AdapterOnItemClick<MemberServiceListBean>() {
            @Override
            public void onItemClick(MemberServiceListBean serviceListEntiy, int position) {
                MemberConfig.getInstance().startWebsiteInfo(getContext(), serviceListEntiy.getNo(), MemberConfig.WEBSITE_FOR_COMPANY);
            }
        });
        mBinding.recyclerView.setAdapter(mAdapter);
    }

    public void closeRecyclerRefreshing() {
        mBinding.recyclerView.refreshComplete();
        mBinding.recyclerView.loadMoreComplete();
    }

    public void showEmpty() {
        closeRecyclerRefreshing();
        mAdapter.clearDatas();
        mBinding.emptyView.setVisibility(View.VISIBLE);
    }

    public void refreshRecycler(List<MemberServiceListBean> list, boolean isLoadMore, boolean noMoreData) {
        mBinding.recyclerView.setVisibility(View.VISIBLE);
        mBinding.recyclerView.setNoMore(noMoreData);
        closeRecyclerRefreshing();
        if (isLoadMore) {
            if (list != null && list.size() > 0) {
                mAdapter.addDatas(list);
            }
        } else {
            if (list != null && list.size() > 0) {
                mBinding.emptyView.setVisibility(View.GONE);
                mAdapter.setDatas(list);
            } else {
                mAdapter.clearDatas();
                mBinding.emptyView.setVisibility(View.VISIBLE);
            }
        }
    }

    /**
     * ------------------------------- Popup ---------------------------------------------
     */
    private void initPopup() {
        mBinding.popAddress.initPopup(mBinding.grayLayout, mBinding.popLine, this);
        mBinding.popupMemberLever.initPopup(mBinding.grayLayout, mBinding.popLine, this);
        mAddressPop = initAddressPopup(mBinding.popAddress);
    }

    private ThreeLevelAreaWindow initAddressPopup(MemberStatusView statusView) {
        ThreeLevelAreaWindow mAddressPop = new ThreeLevelAreaWindow(getActivity());
        mAddressPop.setBgView(mBinding.grayLayout);
        mAddressPop.setMemberHeight();
        mAddressPop.setCitySingle();
        mAddressPop.setProvinceSingle();
        mAddressPop.setShowSimpleName(true);
        mAddressPop.setOnlyShowProAndCity(true);
        mAddressPop.setAllSingleSelect(true);
        mAddressPop.setThreeListIsGone(true);
        mAddressPop.setOnResultClick(new ThreeLevelAreaWindow.OnResultClickProxy() {
            @Override
            protected void result(GoodsSourceLocationEntity entity) {
                statusView.updateChooseTextStatus(0, statusView.getKeyName());
                if (!TextUtils.isEmpty(entity.getProvinceNo())) {
                    statusView.updateChooseTextStatus(1, entity.getProvinceName());
                    if (!TextUtils.isEmpty(entity.getCityNo())) {
                        statusView.updateChooseTextStatus(1, entity.getCityName());
                        if (!TextUtils.isEmpty(entity.getAreaNo())) {
                            statusView.updateChooseTextStatus(1, entity.getAreaName());
                        }
                    }
                }
                mAddressEntity = entity;
                //刷新数据
                loadData(false);
            }
        });
        mAddressPop.setOnDismissListener(() -> {
            mBinding.popLine.setVisibility(View.GONE);
            if (mAddressEntity != null) {
                if (!TextUtils.isEmpty(mAddressEntity.getProvinceNo())) {
                    statusView.updateChooseTextStatus(1, null);
                } else {
                    statusView.updateChooseTextStatus(0, statusView.getKeyName());
                }
            } else {
                statusView.updateChooseTextStatus(0, statusView.getKeyName());
            }
        });
        statusView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (scrData == null) {
                    sModel.getAddressModel();
                    return;
                }
                mBinding.popLine.setVisibility(View.GONE);
                if (mAddressEntity != null) {
                    if (!TextUtils.isEmpty(mAddressEntity.getProvinceNo())) {
                        statusView.updateChooseTextStatus(1, null);
                    } else {
                        statusView.updateChooseTextStatus(0, statusView.getKeyName());
                    }
                } else {
                    statusView.updateChooseTextStatus(0, statusView.getKeyName());
                }
                mAddressPop.showPopwindow0(mBinding.popLine);
            }
        });
        return mAddressPop;
    }

    @Override
    public void onLoadChooseData(String mKeyName) {

    }

    @Override
    public void onChooseResult(String mKeyName, CommonPopEntity entity, Object... objects) {
        int position = (int) objects[0];
        String no = position == 0 ? "" : entity.getNo();
        switch (mKeyName) {
            case "会员级别":
                if (!TextUtils.equals(no, mNo9)) {
                    mNo9 = entity.getId();
                    loadData(false);
                }
                break;
        }
    }

    public void setChooseItemData(int type, List<CommonPopEntity> data, boolean isShowPopup) {
        switch (type) {
            case PickCateType.TYPE_9:
                mBinding.popupMemberLever.setData(data, mNo9);
                break;
        }
    }

}
